package components.paddle;

import java.awt.Color;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.appearances.Rectangle;
import com.uqbar.vainilla.events.constants.Key;
import components.CollisionableComponent;
import components.gamelevels.GameLevel;
import components.powerups.PowerUp;

public class Paddle extends CollisionableComponent<GameLevel> {

	private int speed;
	
	public Paddle(int diameter, int height, int aSpeed, double x, double y){
		super(diameter, height, x, y);
		this.speed = aSpeed;
		this.setAppearance(new Rectangle(Color.BLACK, this.getDiameter(), this.getHeight()));
	}
	public Paddle(int diameter, int height, int aSpeed){
		super(diameter, height, 0, 0);
		this.speed = aSpeed;
		this.setAppearance(new Rectangle(Color.BLACK, this.getDiameter(), this.getHeight()));
	}
	

	private void movePaddle(DeltaState delta, int dir) {
		double intensity = delta.getDelta() * this.getSpeed() * dir;
		double nx, ny;
		nx = this.getX() +intensity;
		ny = this.getY();
		
		if (! this.collide(nx, ny)){
			if (! outOfBounds(nx, ny)){
				this.updateCoords(intensity, 0);
			}
		}
	}


	private boolean outOfBounds(double nx, double ny) {
		return this.getGame().getDisplayWidth() < nx + this.getDiameter() && this.getGame().getDisplayHeight() < ny + this.getHeight();
	}


	public void setSpeed(int speed) {
		this.speed = speed;
	}

	public int getSpeed() {
		return speed;
	}



	@Override
	public boolean isSolid() {
		return true;
	}

	@Override
	protected void onCollisionWithSolid(CollisionableComponent gc) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void defineCollide(CollisionableComponent gc) {
		gc.collideWithPaddle(this);
	}
	
	public void collideWithPowerUp(PowerUp pup){
		this.getScene().runPowerUp(pup);
		pup.destroyComponent();
	}

	@Override
	protected void effectiveUpdate(DeltaState delta) {
		if (delta.isKeyPressed(Key.LEFT) | delta.isKeyBeingHold(Key.LEFT)){
			this.movePaddle(delta, -1);
		}
		else if (delta.isKeyPressed(Key.RIGHT) | delta.isKeyBeingHold(Key.RIGHT)){
			this.movePaddle(delta, 1);
		}
	}
}
